package com.webchat.ugc.service.mall.im.convert;

import com.webchat.common.enums.mall.im.MallIMMessageCardTypeEnum;
import com.webchat.common.enums.mall.im.MallImMessageTypeEnum;
import com.webchat.common.util.JsonUtil;
import com.webchat.domain.vo.dto.mall.im.CardMessageBaseDTO;
import com.webchat.domain.vo.dto.mall.im.UgcServerMessageDTO;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ChatMessageConverter {


    private static Map<Integer, MessageConverter<?>> baseMessageConverterMap = new ConcurrentHashMap<>();
    private static Map<Integer, MessageConverter<?>> cardMessageConverterMap = new ConcurrentHashMap<>();

    static {
        /**
         * 基础消息类型转换器
         */
        baseMessageConverterMap.put(MallImMessageTypeEnum.MSG_TEXT.getTypeCode(), new TextMessageConverter());
        /**
         * 卡片消息类型转换器
         */
        cardMessageConverterMap.put(MallIMMessageCardTypeEnum.CARD_PRODUCT.getType(), new CardProductMessageConverter());
    }

    /**
     * 消息转文本
     *
     * @param msg
     * @return
     */
    public static String text(UgcServerMessageDTO msg) {

        return getMessageConverter(msg).convertTextMessage(msg);
    }

    /**
     * 获取IM消息内容转换器
     *
     * @param ugcServerMessageDTO
     * @return
     */
    private static MessageConverter getMessageConverter(UgcServerMessageDTO ugcServerMessageDTO) {

        if (MallImMessageTypeEnum.isCardMessage(ugcServerMessageDTO.getMessageType())) {

            CardMessageBaseDTO cardMessage = JsonUtil.fromJson(JsonUtil.toJsonString(ugcServerMessageDTO.getMessage()),
                    CardMessageBaseDTO.class);

            return cardMessageConverterMap.get(cardMessage.getCardType());
        }
        return baseMessageConverterMap.get(ugcServerMessageDTO.getMessageType());
    }
}
